package com.example.example;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
//
import java.text.SimpleDateFormat;

public class MainActivity extends AppCompatActivity {
    private Button co;  //一氧化碳按钮初始化
    private Button open;
    private ImageButton wifi_button;
    private TextView iot_laststatus;
    private TextView co_num;
    private TextView wifi_status;
    //MQTT
    private String host = "tcp://106.13.150.28:1883";
    private String userName = "android";
    private String passWord = "android";
    private String mqtt_id = "3528731270";
    private String mqtt_sub_topic = "3528731270"; //订阅主题
    private String mqtt_pub_topic = "3528731270PIOPEN";
    private MqttClient client;
    private MqttConnectOptions options;
    private Handler handler;
    private ScheduledExecutorService scheduler;
    Vibrator vibrator;
    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //*************UI***********//
        ui_init();

        @SuppressLint("SimpleDateFormat") SimpleDateFormat   ID_format   =   new   SimpleDateFormat   ("HH:mm:ss");
        Date ID_curDate =  new Date(System.currentTimeMillis());
        mqtt_id   =   ID_format.format(ID_curDate);   //用时间随机MQTTID


        co.setOnClickListener(new View.OnClickListener() {  //java监听按钮
            @Override
            public void onClick(View view) {
                //点击之后执行的地方
                Toast.makeText(MainActivity.this, "hello", Toast.LENGTH_SHORT).show();
            }
        });

        open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "open", Toast.LENGTH_SHORT).show();
                publishmessageplus(mqtt_pub_topic,"open");
            }
        });
        //**************MQTT***************//
        Mqtt_init();

        startReconnect();

        handler = new Handler() {
            @SuppressLint("SetTextI18n")
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                //显示最后一次接受信息的时间
                @SuppressLint("SimpleDateFormat") SimpleDateFormat   formatter   =   new   SimpleDateFormat   ("HH:mm:ss");
                Date curDate =  new Date(System.currentTimeMillis());
                String   str   =   formatter.format(curDate);
                iot_laststatus.setText("当前数据时间："+str);
                float temp_co = 0;
                String temp_str;
                switch (msg.what){
                    case 1: //开机校验更新回传
                        break;
                    case 2:  // 反馈回传

                        break;
                    case 3:  //MQTT 收到消息回传   UTF8Buffer msg=new UTF8Buffer(object.toString());
                        //Toast.makeText(MainActivity.this,msg.obj.toString() ,Toast.LENGTH_SHORT).show();
                        temp_str = msg.obj.toString();
                        co_num.setText("CO浓度："+msg.obj.toString()+"ppm");
                        try {
                            temp_co = Float.parseFloat(temp_str);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        if(temp_co > 50)
                        {
                            Toast.makeText(MainActivity.this, "警告：CO超标", Toast.LENGTH_SHORT).show();

                            vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);//震动
                            long [] pattern = {100,700,100,700};
                            vibrator.vibrate(pattern,-1);
                        }

                        break;
                    case 30:  //连接失败
                        Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                        wifi_button.setBackgroundResource(R.drawable.diswifi);
                        wifi_status.setText("未连接");
                        break;
                    case 31:   //连接成功
                        Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                        wifi_button.setBackgroundResource(R.drawable.enwifi);
                        wifi_status.setText("连接成功");

                        try {
                            client.subscribe(mqtt_sub_topic,1);
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }
                        break;
                    default:
                        break;
                }
            }
        };
    }
    private void ui_init() {
        co = findViewById(R.id.co); //关联xml里面定义的ID
        iot_laststatus = findViewById(R.id.iot_laststatus);
        open = findViewById(R.id.open);
        co_num = findViewById(R.id.co_num);
        wifi_status = findViewById(R.id.wifi_status);
        wifi_button = findViewById(R.id.wifi_button);
    }

    private void Mqtt_init()
    {
        try {
            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            client = new MqttClient(host, mqtt_id,
                    new MemoryPersistence());
            //MQTT的连接设置
            options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(false);
            //设置连接的用户名
            options.setUserName(userName);
            //设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，一般在这里面进行重连
                    System.out.println("connectionLost----------");
                    //startReconnect();
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    System.out.println("deliveryComplete---------"
                            + token.isComplete());
                }
                @Override
                public void messageArrived(String topicName, MqttMessage message)
                        throws Exception {
                    //subscribe后得到的消息会执行到这里面
                    System.out.println("messageArrived----------");
                    Message msg = new Message();
                    msg.what = 3;   //收到消息标志位
                    msg.obj = message.toString();
                    handler.sendMessage(msg);    // hander 回传
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void Mqtt_connect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if(!(client.isConnected()) )  //如果还未连接
                    {
                        client.connect(options);
                        Message msg = new Message();
                        msg.what = 31;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 30;
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }

    private void startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!client.isConnected()) {
                    Mqtt_connect();
                }
            }
        }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }
    private void publishmessageplus(String topic,String message2)
    {
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setPayload(message2.getBytes());
        try {
            client.publish(topic,message);
        } catch (MqttException e) {

            e.printStackTrace();
        }
    }
}
